import { PageHeader } from "@ant-design/pro-components";
import { Button, Form, Input, message, notification, Select, Steps } from "antd";
import axios from "axios";
import { useState, useEffect, useRef } from "react";
import NewsEditor from "../../../components/NewsEditor";
import { readToken } from "../../../util";
import { useHistory, useParams } from "react-router-dom";
/** @import {FormInstance} from 'antd' */

function isHTMLEmpty(htmlCode) {
    const div = document.createElement('div');
    div.innerHTML = htmlCode;
    return div.innerText.trim() === "";
}

/**
 * 
 * @param {object} props
 * @param {"add"|"update"} [props.type="add"]
 * @returns 
 */
function NewsAdd({ type = "add" }) {
    const [step, setStep] = useState(0);
    const [categories, setCategories] = useState([]);
    const [newsContent, setNewsContent] = useState("");
    /** @type {React.MutableRefObject<FormInstance>} */
    const formRef = useRef();
    const history = useHistory();
    const params = useParams();

    const isUpdate = (type === "update");
    const isAdd = (type === "add");
    const updateNewsId = isUpdate && params.id;
    

    // 拉取数据
    useEffect(() => {
        axios.get("/categories").then((res) => setCategories(res.data));
    }, []);
    useEffect(() => {
        if (!updateNewsId)
            return;
        axios.get("/news/" + updateNewsId)
            .then((res) => {
                formRef.current.setFieldsValue({
                    title: res.data.title,
                    categoryId: res.data.categoryId,
                });
                setNewsContent(res.data.content);
            })
            .catch((err) => console.log(err))
    }, [updateNewsId]);

    const displayOnStep = (targetStep) => ({
        style: { display: targetStep === step ? undefined : "none" },
    });
    const nextStep = () => {
        if (step === 0) { // 编辑标题和分类
            formRef.current.validateFields().then(
                () => setStep(step + 1),
                (err) => console.log(err)
            );
        } else if (step === 1) { // 编辑新闻内容
            if (isHTMLEmpty(newsContent))
                message.error("新闻内容不能为空");
            else
                setStep(step + 1);
        }
    }

    /** @type {(auditState: number) => void} 保存草稿/发布文章 */
    const handleSave = async (auditState) => {
        const token = readToken();
        const formData = await formRef.current.validateFields();
        const method = isAdd? "post" : "patch";
        const url = isAdd? "/news" : `/news/${updateNewsId}`;
        let requestData;
        if (isAdd) {
            requestData = {
                region: token.region === "" ? "全球" : token.region,
                author: token.username,
                roleId: token.roleId,
                auditState: auditState,
                publishState: 0,
                createTime: Date.now(),
                star: 0,
                view: 0,
                publishTime: 0,
                title: formData.title,
                categoryId: formData.categoryId,
                content: newsContent
            };
        } else {
            requestData = {
                title: formData.title,
                categoryId: formData.categoryId,
                content: newsContent,
                auditState: auditState,
            };
        }
        axios.request({
            method: method,
            url: url,
            data: requestData,
        })
        .then(() => {
            if (auditState === 0) // 草稿
                history.push("/news-manage/draft");
            else // 发布
                history.push("/audit-manage/audit");
            notification.success({description: `可在${auditState === 0 ? "草稿箱" : "审核页面"}中查看刚刚发布的文章。`});
        });
    };

    return (
        <PageHeader
            title={isAdd ? "撰写新闻" : "更新新闻"}
            onBack={isUpdate && (() => history.goBack())}
        >
            <Steps
                current={step}
                items={[
                    {
                        title: "基本信息",
                        description: "新闻标题，新闻分类",
                    },
                    {
                        title: "新闻内容",
                        description: "新闻主体内容",
                    },
                    {
                        title: "新闻提交",
                        description: "保存草稿或者提交审核",
                    },
                ]}
            />

            <Form ref={formRef} style={{ marginTop: "25px" }}>
                <div {...displayOnStep(0)}>
                    <Form.Item
                        name="title"
                        label="标题"
                        rules={[{ required: true, message: "请填写标题" }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        name="categoryId"
                        label="分类"
                        rules={[{ required: true, message: "请选择分类" }]}
                    >
                        <Select
                            options={categories.map((c) => ({
                                value: c.id,
                                label: c.title,
                            }))}
                        />
                    </Form.Item>
                </div>
                <div {...displayOnStep(1)}>
                    <NewsEditor content={newsContent} onContentChange={setNewsContent} />
                </div>
            </Form>

            <div style={{ marginTop: "30px", display: "flex", gap: "5px" }}>
                {step > 0 && (
                    <Button onClick={() => setStep(step - 1)}>上一步</Button>
                )}
                {step < 2 && <Button onClick={nextStep}>下一步</Button>}
                {step == 2 && <Button type="primary" onClick={() => handleSave(1)}>发布</Button>}
                {step == 2 && <Button type="primary" onClick={() => handleSave(0)}>保存草稿箱</Button>}
            </div>
        </PageHeader>
    );
}

export default NewsAdd;
